<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table{
            border-collapse: collapse;
            width: 300px;
            margin: 0 auto;
        }
        th,td{
            font-size: 20px;
            text-align: center;
            border: 1px solid #000;
        }
        caption{
            font-size: 30px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h1>fetch的使用2</h1>
    <hr>
    <button id="btn">点我加载数据</button>
    <button id="btn2">点我加载数据2</button>
    <hr>
    <div id="root"></div>

    <script>
        const btn = document.getElementById("btn")
        const btn2 = document.getElementById("btn2")
        const root = document.getElementById("root")

        btn2.onclick = () => {
            fetch("http://localhost:3000/students",{
                method:"POST",
                headers:{
                    "Content-type":"application/json"
                },
                body: JSON.stringify({
                    
                    name:"白骨精",
                    age:"14",
                    gender:"女",
                    address:"白骨洞"
                })

            })
        }


        btn.onclick = () => {
            fetch("http://localhost:3000/students")
            .then((res) => {
               if(res.status === 200){
                    return res.json()
               }else{
                    throw new Error("数据出错误了")
               }
                    
            })
            .then((res) => {
                const table = document.createElement("table")
                root.appendChild(table)
                table.insertAdjacentHTML("beforeend","<caption>学生列表</caption>")
                table.insertAdjacentHTML("beforeend",`
                    <thead>
                        <tr>
                            <th>学号</th>
                            <th>姓名</th>
                            <th>年龄</th>
                            <th>性别</th>
                            <th>地址</th>
                        </tr>    
                    </thead>
                `)

                const tbody = document.createElement("tbody")
                table.appendChild(tbody)
                for(let stu of res.data){
                    tbody.insertAdjacentHTML("beforeend",`
                        <tr>
                            <td>${stu.id}</td> 
                            <td>${stu.name}</td>
                            <td>${stu.age}</td>
                            <td>${stu.gender}</td>
                            <td>${stu.address}</td>
                        </tr>
                    `)
                }
            })

            .catch((err) => {
                console.log("出错了",err);
            })
        }
        
    </script>

</body>
</html>